<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/10 0010
 * Time: 下午 15:25
 */

namespace Home\Controller;
use Think\Controller;
/**
 *客户聊天控制器ChatController
 */

class ChatController extends Controller{
    public function chat_window(){
        /*************************获取当前客户和客服id*******************/
        $userid = I('get.userid');
        $kefuid = I('get.kefuid');
        //判断用户从产品页面进入还是从个人中心进入
        if(!$kefuid){    //从产品页面或供应商页面进入
            $gysno = I('get.gysno');
            $receiver = D('kefu');
            //根据当前的供应商ID取出对应的客服人员,
            $kefuinfo = $receiver->where("gysno={$gysno}")->find();
            if(!$kefuinfo){
                $this->error('抱歉,该供应商暂无客服 ! ');
                exit;
            }
            $kefuid = $kefuinfo['kefu_user'];
        }
        //echo $userid.'-----'.$kefuid;exit;

        /*******************在聊天状态表里查看双方是否存在聊天记录,*******************/
        $onlinemodel = D('online');
        $info = $onlinemodel->search($userid,$kefuid);
        if($info){  //如果存在,更改客户的在线状态为 1
            $onlinemodel->update_online($userid,$kefuid,'user_type',1);
            //未读消息清零
            $onlinemodel->init_num($userid,$kefuid,'user_wd_num');
        }else{   //如果不存在,插入记录
            $onlinemodel->add(array(
                'user_id' => $userid,
                'user_type' => 1,
                'kefu_id' => $kefuid,
            ));
        }
        /*******************取出当前客户和客服的具体信息*****************/
        $usersmodel = D('users');
        $userinfo = $usersmodel->getusersinfo($userid);
        $kefuinfo = $usersmodel->getusersinfo($kefuid);

        /*************************获取当前客户和客服的聊天消息****************************/
        $sendmodel = D('send_msg');
        $arr = $sendmodel->get_msg($userid,$kefuid);
        /**************************获取当前客服和客户的聊天消息的最大ID*******************************/
        $rmaxid = $this->getmaxid($kefuid,$userid);
        //dump($rmaxid);exit;

        $this->assign(array(
            'info' => $arr,  //消息数据
            'rmaxid' => $rmaxid,  //当前客户和客服消息的最大ID
            'userid' => $userid,   //当前客户ID
            'user_img' => $userinfo['avatar'],//当前客户头像
            'kefuid' => $kefuid,    //当前客服ID
            'kefu_name' => $kefuinfo['name'],//当前客服名称
            'kefu_img' => $kefuinfo['avatar'],//当前客服头像
        ));
        $this->display();
    }

    //把当前userid的会话状态改为0(下线状态)
    public function update_useronline(){
        $userid = I('get.userid');
        $kefuid = I('get.kefuid');
        $user_type = I('get.user_type');

        $onlinemodel = D('online');
        $onlinemodel->update_online($userid,$kefuid,$user_type,0);
        $this->ajaxReturn(true);
    }

    public function ajax_getuseridonline(){
        $userid = I('get.userid');
        $kefuid = I('get.kefuid');
        $user_type = I('get.user_type');
        $onlinemodel = D('online');
        $type = $onlinemodel->get_useridonline($userid,$kefuid,$user_type);
        $this->ajaxReturn($type);
    }


    //从数据库里取出最新消息
    public function ajax_getmsg(){
        $rmaxid = I('get.rmaxid');
        $userid = I('get.userid');
        $kefuid = I('get.kefuid');
        $rmaxid_new = $this->getmaxid($kefuid,$userid);
        $arr = false;
        if($rmaxid_new > $rmaxid){
            $receiver = D()->query("select * from receiver_msg where send_id='{$kefuid}' and receiver_id='{$userid}' and id>{$rmaxid} order by time asc");
            $arr = $receiver;
        }
        //dump($arr);exit;
        $this->ajaxReturn(array(
            'info' => $arr,
            'rmaxid' => $rmaxid_new,
        ));
    }

    public function getmaxid($kefuid,$userid){
        $info = D()->query("select max(id) maxid from receiver_msg where send_id='{$kefuid}' and receiver_id='{$userid}'");
        return $info[0]['maxid'] ? $info[0]['maxid'] : 0;
    }



    //推送信息
    public function fsmsg(){
        $user_id = I('get.user_id');//客户ID
        $kefu_id = I('get.kefu_id'); //客服ID
        $user_type = I('get.user_type');  //要给谁发消息 user_type=yonghu表示给客户发消息 or user_type=kefu表示给客服发消息

        //根据传过来的user_type
        if($user_type == 'kefu'){
            $send_id = $user_id;  //来自客户发送  发放方
            $receiver_id = $kefu_id;  //发送给客服  接收方
        }elseif($user_type == 'yonghu'){
            $send_id = $kefu_id;    //来自客服发送  发放方
            $receiver_id = $user_id; //发送给客户  接收方
        }
        $usersmodel = D('users');
        $user_name = $usersmodel->get_username($send_id);

        $appurl = C('APPURL');
        $url = "{$appurl}/Home/User/kefu_msg/userid/{$receiver_id}/receiver_id/{$send_id}/type/{$user_type}";
        // dump($username);exit;
        $articles[] = array(
            'title' => urlencode('消息提醒'),
            'description' => urlencode('来自'.$user_name.'聊天信息'),
            'url' => $url,
            'picurl' => ''
        );
        $access_token = componentsgetaccesstoken(); //获取access_token
        $articles = array('articles' => $articles);
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token";
        $post = array(
            'touser'   => $receiver_id,
            'toparty'  => '',
            'totag'    => '',
            'msgtype'  => 'news',
            'agentid'  => C('CORPID'),
            'news'     => $articles
        );
        $post = urldecode(json_encode($post));
        //发送请求
        //dump($post);exit;
        $res = json_decode(https_request($url, $post),true);
        //检测消息发送是否成功
        if($res['errorcode']==0){
            $this->ajaxReturn(true);
        }else{
            $this->ajaxReturn(false);
        }
    }


}
